package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.NewAuthDto;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.*;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: TODO
 * @Description: TODO
 * @author: 丁丁
 * @date: 2021/3/17
 * @version:
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 设置分页参数
        IPage pageParam = new Page(dto.getPage(), dto.getSize());
        // 构造查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //关键字模糊查询
        if (dto.getKeyWord() != null) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyWord());
        }
        // 查询登录用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        // 根据时间降序排列
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        // 查询数据
        IPage result = page(pageParam, lambdaQueryWrapper);
        // 封装结果，返回数据
        ResponseResult pageResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        pageResult.setData(result.getRecords());
        pageResult.setHost(fileServerUrl);
        return pageResult;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        // 检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 封装文章对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // 判断当前文章是否自动匹配封面
        if (WemediaContans.WM_NEWS_AUTO_TYPE.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // 判断是否有封面图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imgStr = dto.getImages().toString().replace("[", "").replace("]", "")
                    .replace(fileServerUrl, "").replace(" ", "");
            wmNews.setImages(imgStr);
        }
        // 保存或修改文章
        saveWmNews(wmNews, isSubmit);
        // 建立文章中素材和素材表之间的关联关系
        // 获取文章内容中的图片
        String content = dto.getContent();
        // 将内容转换成json对象，方便获取图片
        List<Map> lists = JSON.parseArray(content, Map.class);
        // 获取对象中的图片
        List<String> materialsImgFromContent = getImgUrlFromContent(lists);
        // 关联内容中的图片与素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materialsImgFromContent.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForContent(materialsImgFromContent, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        // 关联封面中的图片与素材的关系,设置wm_news的type,自动
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            ResponseResult responseResult = saveRelativeInfoForCover(dto, wmNews, materialsImgFromContent);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面素材和文章之间的关联关系
     *
     * @param dto
     * @param wmNews
     * @param materialsImgFromContent
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materialsImgFromContent) {
        List<String> images = dto.getImages();
        // 判断是否为自动匹配封面
        if (dto.getType().equals(WemediaContans.WM_NEWS_AUTO_TYPE)) {
            //内容中的图片数量小于等于2  设置为单图
            if (materialsImgFromContent.size() > 0 && materialsImgFromContent.size() <= 2) {
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_TYPE);
                images = materialsImgFromContent.stream().limit(1).collect(Collectors.toList());
            } else if (materialsImgFromContent.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WemediaContans.WM_NEWS_MANY_TYPE);
                images = materialsImgFromContent.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WemediaContans.WM_NEWS_NONE_TYPE);
            }
            // 修改信息
            if (images.size() > 0) {
                String imgUrl = images.toString().replace("[", "").replace("]", "")
                        .replace(fileServerUrl, "").replace(" ", "");
                wmNews.setImages(imgUrl);
            }
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForImage(images, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    /**
     * 保存关系
     *
     * @param images
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer newsId) {
        List<String> materials = new ArrayList<>();
        for (String image : images) {
            materials.add(image.replace(fileServerUrl, ""));
        }
        return saveRelativeInfo(materials, newsId, WemediaContans.WM_NEWS_COVER_REFERENCE);
    }

    /**
     * 保存内容中图片素材和文章的关联关系
     *
     * @param materialsImgFromContent
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materialsImgFromContent, Integer newsId) {
        return saveRelativeInfo(materialsImgFromContent, newsId, WemediaContans.WM_NEWS_CONTENT_REFERENCE);
    }

    /**
     * 保存图片素材和文章关系
     *
     * @param materialsImgFromContent
     * @param newsId
     * @param type
     * @return
     */
    private ResponseResult saveRelativeInfo(List<String> materialsImgFromContent, Integer newsId, Short type) {
        // 获取素材库中素材URL对应的id
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materialsImgFromContent);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);
        // 根据图片获取素材id
        List<String> materialsIds = new ArrayList<>();
        if (wmMaterials != null && wmMaterials.size() > 0) {
            Map<String, Integer> uriIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            for (String val : materialsImgFromContent) {
                String materialId = String.valueOf(uriIdMap.get(val));
                if ("null".equals(materialId)) {
                    // 没找到
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                }
                // 找到了
                materialsIds.add(materialId);
            }
        }
        //3.批量保存数据
        wmNewsMaterialMapper.saveRelationsByContent(materialsIds, newsId, type);
        return null;
    }

    /**
     * 提取图片URL
     *
     * @param lists
     * @return
     */
    private List<String> getImgUrlFromContent(List<Map> lists) {
        List<String> imgUrls = new ArrayList<>();
        for (Map map : lists) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                imgUrls.add(imgUrl);
            }
        }
        return imgUrls;
    }

    /**
     * 保存或修改自媒体文章信息
     *
     * @param wmNews   自媒体文章信息
     * @param isSubmit 0 草稿
     *                 1 提交（待审核）
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        // 设置文章参数
        wmNews.setStatus(isSubmit);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setEnable((short) 1);
        // 保存修改或删除操作结果，用于发送kafka消息
        boolean flag = false;
        // 判断改文章是否有id，有id就是保存草稿，没有id就是新建文章
        if (wmNews.getId() == null) {
            flag = save(wmNews);
        } else {
            //如果是修改，则先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            flag = updateById(wmNews);
        }
        // 操作成功，发送消息，提示运营端审核
        if (flag) {
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        }
    }

    /**
     * 根据id获取文章信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        // 查询数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 封装返回数据
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        // 检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        // 查询数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_ENABLE_UP)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        // 去除素材关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        // 删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上或下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 判断是否已经发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            // 未发布
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        // 修改状态
        if (wmNews.getEnable() != null && wmNews.getEnable() > -1 && wmNews.getEnable() < 2) {
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询自媒体文章信息
     *
     * @param id
     * @return
     */
    @Override
    public WmNews findById(Integer id) {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 修改自媒体文章信息
     *
     * @param wmNews
     * @return
     */
    @Override
    public ResponseResult updateWmnews(WmNews wmNews) {
        // 检查参数
        if (wmNews == null || wmNews.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改数据
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询待发布文章的id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer> collect = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return collect;
    }

    /**
     * 分页查询所有文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findListAndPage(NewAuthDto dto) {
        // 检查参数
        if (dto == null) {
            return null;
        }
        dto.checkParam();
        // 设置分页参数
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        dto.setTitle("%" + dto.getTitle() + "%");
        // 查询数据
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        // 查询符合条件的总共有多少条数据
        int count = wmNewsMapper.findListCount(dto);
        // 封装参数，返回数据
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        result.setData(listAndPage);
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        // 检查参数
        if (id == null) {
            return null;
        }
        // 查询文章信息
        WmNews wmNews = getById(id);
        WmUser wmUser = null;
        if (wmNews != null && wmNews.getUserId() != null) {
            // 查询作者
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        // 封装返回参数
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthName(wmUser.getName());
        }
        return wmNewsVo;
    }
}
